import os
import re

from lxml import etree

from settings import web_type
from util import http_utils
from util.DataQuery.DbTools import DbTools
from util.DataQuery.hzflowOperation import hzflowOperation
from util.g import g
from util.inform.sendNote import AliyunSMS
from util.selenium.webdriver.common.by import By

from base.BaseMethod import BM



class ToLeftThree():


    top_frame_loc = (By.CSS_SELECTOR, 'iframe')

    left_frame_loc = (By.CSS_SELECTOR, 'frame#leftFrame')

    # 调查监测窗口
    box_loc = (By.XPATH, "//div[@id='jBox_quarter']")

    box_title_loc = (By.XPATH, "//div[@id='jBox_quarter']//div[@class='jbox-title']")

    title_h_loc = (By.CSS_SELECTOR, "h2")

    creditcode_loc = (By.XPATH, "//div[@class='userInfo']/ul[2]/li[6]")

    accept_loc = (By.CSS_SELECTOR, ".btnBox .btn.ok")

    # left_three_btn_loc = (By.CSS_SELECTOR, 'ul#transmitId li:nth-child(3) a')
    left_three_btn_loc = (By.XPATH, "//ul[@id='transmitId']//a[contains(text(),'高企认定申报')]")

    def __init__(self, driver, status=None):
        self.driver = driver
        self.status = status

    def to_left_three(self):

        BM.close_current_page(driver=self.driver)
        page_list = self.driver.window_handles
        if len(page_list) > 1:
            self.driver.switch_to.window(page_list[-1])

        # 国网是否实名认证
        if BM.isElementExist(element=self.title_h_loc, driver=self.driver):
            tip = self.driver.find_element(*self.title_h_loc).text
            if u"未实名认证" in tip:
                status = self.status
                map = {"ul_status": -1, "c_idstatus": 1}
                DbTools.update_entrestatus_fields(map, co_id=g.co_id, year=g.year)
                hzflowOperation.update_host_process(obj=hzflowOperation.get_log(g.co_id, g.year), mark_info="")
                AliyunSMS().send_single(
                    phone=status.get("phone"), template="SMS_193244862",
                    params={"resinfo": "{}, 企业国网账号未实名认证。请前往国网进行实名认证后，到市网重新保存国网账号密码激活上传。".format(status.get("entname"))},
                    fb_time=status.get("fb_time"), res_code=web_type)
            self.driver.quit()
            return True

        # 国网监测季度调查表填写短信
        if BM.isElementExist(element=self.box_loc, driver=self.driver):
            status = self.status
            map = {"ul_status": -1, "c_idstatus": 1}
            DbTools.update_entrestatus_fields(map, co_id=g.co_id, year=g.year)
            hzflowOperation.update_host_process(obj=hzflowOperation.get_log(g.co_id, g.year), mark_info="")
            AliyunSMS().send_single(
                phone=status.get("phone"), template="SMS_193244862",
                params={"resinfo": "{}, 请填写国网监测季度调查表。完成后前往市网重新保存国网账号密码激活上传。".format(status.get("entname"))},
                fb_time=status.get("fb_time"), res_code=web_type)
            self.driver.quit()
            return True

        if BM.isElementExist(element=self.accept_loc, driver=self.driver):
            if g.record.check_acc_status == -1:
                self.driver.quit()
                return True
            if g.record.check_acc_status == 0:
                # 当确认按钮出现时 取到统一社会信用代码 与 ent_res_status 中的统一社会信用代码对比
                # 如果不一样给企业发短信提示
                creditcode_ele = BM.get_ele(driver=self.driver, ele_loc=self.creditcode_loc, time=6)
                creditcode = creditcode_ele.text
                g.logger.info("当前账号: {}--- 企业: {}".format(creditcode, g.status.get("creditcode")))
                if not g.status.get("creditcode") in creditcode:
                    # 发短信提示客户账号写错了
                    status = self.status
                    map = {"ul_status": -1, "c_idstatus": 1}
                    DbTools.update_entrestatus_fields(map, co_id=g.co_id, year=g.year)
                    hzflowOperation.update_host_process(obj=hzflowOperation.get_log(g.co_id, g.year), mark_info="")
                    AliyunSMS().send_single(
                        phone=status.get("phone"), template="SMS_193244862",
                        params={"resinfo": "{}，请确认国网帐号与公司对应，请前往市网修改后激活上传".format(
                            status.get("entname"))},
                        fb_time=status.get("fb_time"), res_code=web_type)
                    hzflowOperation.update_fields(map={"check_acc_status": -1})
                    hzflowOperation.tran_to_data(co_id=g.co_id, year=g.year, status=6)
                    self.driver.quit()
                    return True
                else:
                    hzflowOperation.update_fields(map={"check_acc_status": 1})
            BM.click(driver=self.driver, ele_loc=self.accept_loc)

        BM.wait(driver=self.driver, ele_loc=self.top_frame_loc, time=20)

        BM.cut_over_frame(self.driver, self.top_frame_loc)

        self.driver.switch_to.parent_frame()
        # BM.cut_over_frame(self.driver, self.left_frame_loc)
        if g.withdrow or g.is_first_entry:
            url = "https://gqqy.chinatorch.org.cn/xonlinereport/inforeport/DataInnocom/list.do"
            BM.get_cookie(driver=self.driver)
            res = http_utils.send_get(url, driver=self.driver)
            text = res.get("text")
            tree = etree.HTML(text)
            materials_list = tree.xpath("//form[@id='DataInnocom_list']/div[2]/div[2]/div[2]/table/tbody/tr")
            for materials in materials_list:
                materials_year = ''.join(materials.xpath("./td[1]/text()"))
                materials_status = ''.join(materials.xpath("./td[4]/text()"))
                materials_del_url = ''.join(materials.xpath("./td[5]/a[2]/@href"))
                if str(g.year) in materials_year:
                    if '申报材料填写中' in materials_status or "退回" in materials_status:
                        re_str = """'(.*)'"""
                        url = 'https://gqqy.chinatorch.org.cn' + ''.join(re.findall(re_str, materials_del_url))
                        del_requests_rst = http_utils.send_get(url=url, driver=self.driver)
                        s = del_requests_rst.get("message")
                        # s = 'var alertMessage = "删除成功";'
                        if u"成功" in s:
                            print("删除材料")
                        else:
                            ''.join(re.findall("""var alertMessage = "(.*)";""", del_requests_rst.text))
                        del_ok = True
                    else:
                        print(materials_status)
            # 更新本地 撤回次数
            record = hzflowOperation.get_log(co_id=g.co_id, year=g.year)
            if g.status:
                up_map = {"fb_time": g.status.get("fb_time")}
                # 第一次录入删除
                if g.is_first_entry:
                    up_map["first_entry_delete"] = 1
                hzflowOperation.update_fields(record, map=up_map)
            # # 删除附件
            # if g.need_file:
            #     ent_material_path = BM.get_material_path()
            #     if os.path.exists(ent_material_path):
            #         BM.remove_dir(dir=ent_material_path)
            # # 清空本地状态信息
            hzflowOperation.emptyProcess(record=record)
            g.record = hzflowOperation.get_log(co_id=g.co_id, year=g.year)
            # 更新撤回信息结束

        BM.click(driver=self.driver, ele_loc=self.left_three_btn_loc)

        return False
